package cn.jnetty.utils.create.excel;

import cn.jnetty.utils.create.OverlookField;
import cn.jnetty.utils.create.proxy.JnettyClassExplain;
import cn.jnetty.utils.create.proxy.JnettyFieldExplain;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 猪哥亮
 * @email 1030681978@qq.com
 * @date 2020/3/29 17:18
 * 描述：根据java对象生成excel表
 */
public class ExcelCreateByJavaClass {
    private static Logger log = LoggerFactory.getLogger(ExcelCreateByJavaClass.class);
    public static void scan(String packageName, String createPath) {
        List<Class> clazzs = GetFileAllInit.getClasssFromPackage(packageName);
        if (clazzs.size() <= 0) {
            return;
        }
        List<Class> resultList = new ArrayList<>();
        for (Class c : clazzs) {
            Annotation excel = c.getAnnotation(JnettyDataTable.class);
            if (excel instanceof JnettyDataTable) {
                resultList.add(c);
            }
        }
        for (Class aClass : resultList) {
            getObjectFields(aClass, createPath);
        }
    }

    /**
     * 获取对象字段
     *
     * @param clazz
     */
    private static void getObjectFields(Class clazz, String createPath) {
        Field[] subFields = clazz.getDeclaredFields();
        Class parentClazz = clazz.getSuperclass();
        while (parentClazz != Object.class && !parentClazz.isInterface()) {
            int srcLength = subFields.length;
            Field[] superFields = parentClazz.getDeclaredFields();
            subFields = Arrays.copyOf(subFields, subFields.length + superFields.length);
            System.arraycopy(superFields, 0, subFields, srcLength, superFields.length);
            parentClazz = parentClazz.getSuperclass();
        }
        removeOverlookField(subFields, clazz, createPath);
    }

    /**
     * 删除或略字段
     *
     * @param fields
     */
    private static void removeOverlookField(Field[] fields, Class clazz, String createPath) {
        if (fields == null || fields.length == 0) {
            return;
        }
        List<Field> list = new ArrayList<>(fields.length);
        for (Field field : fields) {
            Annotation ann = field.getAnnotation(OverlookField.class);
            if (ann instanceof OverlookField) {
                continue;
            }
            list.add(field);
        }
        createExcel(list, clazz, createPath);
    }

    /**
     * 根据字段创建excel表
     *
     * @param list
     */
    private static void createExcel(List<Field> list, Class clazz, String createPath) {
        //创建HSSFWorkbook
        XSSFWorkbook wb = new XSSFWorkbook();
        //第二步创建sheet


        XSSFSheet sheet = wb.createSheet(clazz.getSimpleName());
        //第三步创建行row:添加表头0行
        XSSFCellStyle style = wb.createCellStyle();
        //居中
        style.setAlignment(HorizontalAlignment.CENTER);
        XSSFRow row = null;
        for (int i = 0; i < 3; i++) {
            row = sheet.createRow(i);
            for (int j = 0; j < list.size(); j++) {
                //第四步创建单元格
                //第一个单元格
                XSSFCell cell = row.createCell(j);
                //设定值
                cell.setCellValue(list.get(j).getName());
                if (i == 0) {
                    Annotation annotation = clazz.getAnnotation(JnettyClassExplain.class);
                    if (annotation instanceof JnettyClassExplain) {
                        cell.setCellValue(((JnettyClassExplain) annotation).value());
                    }
                } else if (i == 2) {
                    Annotation annotation = list.get(j).getAnnotation(JnettyFieldExplain.class);
                    if (annotation instanceof JnettyFieldExplain) {
                        cell.setCellValue(((JnettyFieldExplain) annotation).value());
                    }
                }
                //内容居中
                cell.setCellStyle(style);
            }
        }
        //第六步将生成excel文件保存到指定路径下
        try {
            StringBuilder excelName = new StringBuilder();
            excelName
                    .append(Character.toLowerCase(clazz.getSimpleName().charAt(0)))
                    .append(clazz.getSimpleName().substring(1))
                    .append("_")
                    .append(clazz.getName())
                    .append(".xlsx");
            /**如果没有文件夹就自动生成------------------------------------*/
            File file = new File(createPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(createPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            /**如果没有文件夹就自动生成------------------------------------*/
            //首字母小写
            FileOutputStream fout = new FileOutputStream(createPath + excelName.toString());
            wb.write(fout);
            fout.close();
        } catch (IOException e) {
            log.error("将生成excel文件保存到指定路径下时出现异常", e);
        }
    }
}
